module('lgx.gens.alien', package.seeall)
local decl     = require'lgx.decl'
local strbuf   = require'lgx.strbuf'
local utils    = require'lgx.utils'

LIBNAME = ''

function newcell(o)
    o.stdcall = false
    return o
end

local typemap = {
    ['unsigned int'] = 'int',
    ['char'] = 'byte',
    ['signed char'] = 'byte',
    ['unsigned char'] = 'char',
    ['unsigned long'] = 'long',
    ['short int'] = 'short',
    ['short unsigned int'] = 'short',
}
function alientype(info)
    if info.functype then return '"callback"' end
    if info.ptype or info.atype then return '"pointer"' end
    local s = info.decl.name
    s = typemap[s] or s
    return '"'..(info.rtype and 'ref '..s or s)..'"'
end

function alientypes(cell)
    assert(cell.returns)
    local buf = strbuf.new(cell.stdcall and 'abi="stdcall"' or '')
    local rinfo = cell:typeinfo(cell.returns)
    buf = buf + ('ret='..alientype(rinfo))
    if not cell.args then return tostring(buf) end
    for i,v in ipairs(cell.args) do
        buf = buf + alientype(cell:typeinfo(v.type))
    end
    return buf:concat(', ')
end

function Function(cell, cf)
    return string.format('alien.%s.%s:types{%s}', LIBNAME, cell.name, alientypes(cell))
end

